@echo off
:: 设置代码页为 UTF-8
chcp 65001 >nul
setlocal enabledelayedexpansion

:: 设置控制台字体
reg add "HKEY_CURRENT_USER\Console" /v "FontFamily" /t REG_DWORD /d 0x36 /f >nul
reg add "HKEY_CURRENT_USER\Console" /v "FontWeight" /t REG_DWORD /d 0x190 /f >nul

:: 检查管理员权限
net session >nul 2>&1
if %errorLevel% == 0 (
    echo [INFO] 已获取管理员权限
) else (
    echo [ERROR] 请以管理员身份运行此脚本
    echo [INFO] 右键点击脚本，选择"以管理员身份运行"
    pause
    exit /b 1
)

:: 检查并停止可能占用端口的服务
echo [INFO] 检查端口占用...
net stop was /y >nul 2>&1
net stop w3svc >nul 2>&1

:: 检查 Docker 是否运行
docker info >nul 2>&1
if %errorLevel% == 0 (
    echo [INFO] Docker 服务正在运行
) else (
    echo [WARN] Docker 服务未运行，正在尝试启动...
    net start com.docker.service
    timeout /t 10 /nobreak >nul
)

:: 清理旧容器和镜像
echo [INFO] 停止并删除旧容器...
docker-compose down --remove-orphans

echo [INFO] 删除旧镜像...
for /f "tokens=*" %%i in ('docker images -q') do docker rmi %%i -f

:: 清理构建缓存
echo [INFO] 清理 Docker 构建缓存...
docker builder prune -f

:: 设置默认值
set "MYSQL_ROOT_PASSWORD=123456"
set "MYSQL_DATABASE=admin_app"
set "MSSQL_SA_PASSWORD=YourStrong@Passw0rd"

:: 检查配置文件是否存在
if not exist "server\config.json" (
    echo [INFO] 创建默认配置文件...
    mkdir server 2>nul
    (
        echo {
        echo   "databaseType": "sqlite",
        echo   "databaseConfig": {
        echo     "sqlite": {
        echo       "storage": "./database.sqlite"
        echo     },
        echo     "mysql": {
        echo       "host": "mysql",
        echo       "port": 3306,
        echo       "username": "root",
        echo       "password": "%MYSQL_ROOT_PASSWORD%",
        echo       "database": "%MYSQL_DATABASE%"
        echo     },
        echo     "sqlserver": {
        echo       "server": "sqlserver",
        echo       "port": 1433,
        echo       "user": "sa",
        echo       "password": "%MSSQL_SA_PASSWORD%",
        echo       "database": "admin_app"
        echo     }
        echo   }
        echo }
    ) > server\config.json
)

:: 检查 SSL 证书
if not exist "nginx\ssl\server.crt" (
    echo [INFO] 生成 SSL 证书...
    call generate-ssl.bat
)

:: 重新构建并启动容器
echo [INFO] 重新构建镜像...
docker-compose build --no-cache

echo [INFO] 启动新容器...
docker-compose up -d

:: 显示容器状态
echo.
echo [INFO] 容器状态：
docker-compose ps

:: 等待服务就绪
echo.
echo [INFO] 等待服务就绪...
timeout /t 10 /nobreak >n

:: 显示日志
echo.
echo [INFO] 应用日志：
docker-compose logs -f app

endlocal 